package cn.school.workflow.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.school.common.exception.ApiException;
import cn.school.common.utils.SysUserUtils;
import cn.school.workflow.dao.QuitApplyDao;
import cn.school.workflow.service.QuitApplyService;
import cn.school.workflow.service.WorkFlowCommonService;
import cn.school.workflow.vo.QuitApplyVO;
import cn.school.workflow.vo.WorkFlowVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.activiti.engine.RuntimeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;

@Service
public class QuitApplyServiceImpl extends ServiceImpl<QuitApplyDao, QuitApplyVO> implements QuitApplyService {
    @Autowired
    private WorkFlowCommonService workFlowCommonService;
    @Autowired
    private RuntimeService runtimeService;

    @Override
    public IPage<QuitApplyVO> findQuitApplyPageList(QuitApplyVO vo) {
        LambdaQueryWrapper<QuitApplyVO> wrapper = new LambdaQueryWrapper<>();
        //添加租户条件
        wrapper.eq(QuitApplyVO::getTenantId,vo.getTenantId());
        if(!SysUserUtils.getSysUser().getDeptName().startsWith("人事")){
            //默认查询自己提交的申请
            wrapper.eq(QuitApplyVO::getCreateBy,SysUserUtils.getSysUser().getUsername());
        }
        if(!StringUtils.isEmpty(vo.getApplyNo())){
            wrapper.eq(QuitApplyVO::getApplyNo,vo.getApplyNo());
        }
        if(!StringUtils.isEmpty(vo.getQuitDate())){
            wrapper.eq(QuitApplyVO::getQuitDate,vo.getQuitDate());
        }
        wrapper.orderByDesc(QuitApplyVO::getCreateTime);
        return page(new Page<>(vo.getPageNum(), vo.getPageSize()), wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addOrUpdateQuitApply(QuitApplyVO vo) {
        LambdaQueryWrapper<QuitApplyVO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(QuitApplyVO::getCreateBy,SysUserUtils.getSysUser().getUsername());
        wrapper.eq(QuitApplyVO::getStatus,"1");
        int count = this.baseMapper.selectCount(wrapper);
        if(count>1){
            return -1;
        }
        String username = SysUserUtils.getSysUser().getUsername();
        //查询下级处理人
        List<String> approvalUser = getApprovalUser(vo);
        String applyNo = DateUtil.format(new Date(),"yyyyMMddHHmmssSSS");
        vo.setApplyNo("Q"+applyNo);
        vo.setCreateTime(new Date());
        vo.setCreateBy(username);
        //下级审批人
        vo.setCurrApprovedBy(org.apache.commons.lang.StringUtils.join(approvalUser,","));
        this.baseMapper.insert(vo);//添加申请单

        WorkFlowVO flowVO = new WorkFlowVO();
        flowVO.setApplyTitle("离职申请");
        flowVO.setApplyID("quitApply");
        flowVO.setBusinessKey(applyNo);


        Map<String,Object> map =new HashMap<>();
        map.put("assigneeList",approvalUser);
        map.put("flag", "1");
        map.put("userType", "master");
        flowVO.setVariables(map);
        //创建请假工作流
        String processInstanceId = workFlowCommonService.createProcessInstance(flowVO);
        vo.setProcessId(processInstanceId);
        return this.baseMapper.updateById(vo);
    }

    /**
     * 获取选择部门的审批人
     * @param vo
     * @return
     */
    private List<String> getApprovalUser(QuitApplyVO vo) {
        String deptStr = vo.getApprovedDept();
        String[] deptLevelItem = deptStr.split(";");
        List<Long> deptList= new ArrayList<>();
        for (String str:deptLevelItem){
            String [] deptIds = str.split(",");
            deptList.add(Long.valueOf(deptIds[deptIds.length-1]));
        }
        List<String> approvalUser = workFlowCommonService.findAssigneeList(deptList);
        return approvalUser;
    }

    @Override
    @Transactional(rollbackFor = ApiException.class)
    public boolean deleteQuitApplyById(WorkFlowVO vo) throws ApiException{
        boolean flag = workFlowCommonService.cancelApply(vo.getProcessInstanceId(),vo.getApplyDesc());
        if(!flag){
            throw new ApiException("撤销流程失败");
        }
        LambdaQueryWrapper<QuitApplyVO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(QuitApplyVO::getProcessId,vo.getProcessInstanceId());
        QuitApplyVO quitApplyVO = new QuitApplyVO();
        quitApplyVO.setStatus("4");//撤销流程
        quitApplyVO.setModifyBy(SysUserUtils.getSysUser().getUsername());
        quitApplyVO.setModifyTime(new Date());
        this.baseMapper.update(quitApplyVO,wrapper);
        return flag;
    }

    @Override
    public QuitApplyVO findQuitApplyDetail(Long processInstanceId) {
        LambdaQueryWrapper<QuitApplyVO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(QuitApplyVO::getProcessId,processInstanceId);
        return this.baseMapper.selectOne(wrapper);
    }
}
